package com.itheima.reggie.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.Mapper.DishMapper;
import com.itheima.reggie.Service.DishFlavorService;
import com.itheima.reggie.Service.DishService;
import com.itheima.reggie.Sharing.DishOrDishDlavor;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    //新增
    @Override
    @Transactional
    public void addDish(DishOrDishDlavor dishOrDishDlavor) {
       dishService.save(dishOrDishDlavor);
       List<DishFlavor> list= dishOrDishDlavor.getFlavors();
        //菜品Id
        Long Did=dishOrDishDlavor.getId();
       for(  DishFlavor o:list)
       {

          o.setDish_id(Did);
       }
       dishFlavorService.saveBatch(list);
    }
//回显
    @Override
    public DishOrDishDlavor update(Long id) {

        DishOrDishDlavor dishDlavor=new DishOrDishDlavor();
        //查询id为{id}的菜品信息
        Dish dish=dishService.getById(id);
        //查询id为{id}的口味信息
        QueryWrapper<DishFlavor> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dish_id",dish.getId());
       List<DishFlavor> dishFlavors=dishFlavorService.list(queryWrapper);
         //拷贝复制
        BeanUtils.copyProperties(dish,dishDlavor);
       dishDlavor.setFlavors(dishFlavors);
        return dishDlavor;
    }
    //修改
    @Override
    public DishOrDishDlavor save(DishOrDishDlavor dishDlavor)
    {
        //获取菜品id
        Long Did=dishDlavor.getId();
        //更新Dish表的信息
      dishService.updateById(dishDlavor);
        //更新口味表的信息
        List<DishFlavor> dishFlavors=dishDlavor.getFlavors();

        for(DishFlavor o:dishFlavors)
        {
            o.setDish_id(Did);
        }

        dishFlavorService.updateBatchById(dishFlavors);


        return dishDlavor;
    }

}
